package com.example.li.utils;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {
private final static OkHttpClient okHttpClient=new OkHttpClient();
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onBackPressed() {
//        getTest();
//        postTest();
    }

    /**
     * get 请求 异步
     * @param url  传一个地址进来
     */
    private void getTest(String url){
//        String url = "http://location.ximalaya.com/location-web/location?latitude=22.535456&longitude=114.013493";
        Request build = new Request.Builder().url(url).build();
        okHttpClient.newCall(build).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: "+response.body().string());
            }
        });
    }

    /**
     * post 请求
     * @param url 地址
     * @param type
     * @param postText 上传的内容
     */
    private void postTest(String url,String type,String postText){
//        String url="http://127.0.0.1:8080/home/pullText";
//        String type="text/xml; charset=utf-8";
        MediaType TYPE_TEXT = MediaType.parse(type);
//        String postText="要提交的文本内容";
        RequestBody requestBody = RequestBody.create(TYPE_TEXT, postText);
        Request build = new Request.Builder().url(url).post(requestBody).build();
        okHttpClient.newCall(build).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: "+response.body().string());
            }
        });
    }

    /**
     * post 请求
     * @param url 地址
     * @param type
     * @param jsonText  json数据
     */
    private void postJson(String url,String type,String jsonText){
//        String url="http://127.0.0.1:8080/home/pullJson";
        MediaType TYPE_JSON = MediaType.parse(type);
//        String jsonText = "dfsdf";
        RequestBody rb = RequestBody.create(TYPE_JSON, jsonText);
        Request build = new Request.Builder().url(url).post(rb).build();
        okHttpClient.newCall(build).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
    }

    /**
     * post 请求
     * @param url 地址
     * @param formBody 键值对
     * @throws IOException
     */
    private void postKeyValue(String url,FormBody formBody) throws IOException {
//        String url="http://127.0.0.1:8080/home/login";
//
//          FormBody formBody = new FormBody.Builder()
//                .addEncoded("name", "张三")
//                .add("age", "18")
//                .build();
        Request build1 = new Request.Builder().url(url).post(formBody).build();
        Response execute = okHttpClient.newCall(build1).execute();
        String string = execute.body().string();
        Log.d(TAG, "postKeyValue: "+string);
    }

    /**
     * post 上传文件与键值对
     * @throws IOException
     */
    private void postFile() throws IOException {
        MediaType TYPE_FILE = MediaType.parse("application/octet-stream");
        File file1 = new File("x.png");
        RequestBody requestBody1 = RequestBody.create(TYPE_FILE, file1);

        File file2 = new File("j.jpeg");
        RequestBody requestBody2 = RequestBody.create(TYPE_FILE, file2);

        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.MIXED)
                .addFormDataPart("name", "zhangsan")
                .addFormDataPart("psw", "123456")
                .addFormDataPart("f1", file1.getName(), requestBody1)
                .addFormDataPart("f2", file2.getName(), requestBody2)
                .build();

        Request build = new Request.Builder().url("http://127.0.0.1:8080/home/upload").post(multipartBody).build();
        Response execute = okHttpClient.newCall(build).execute();
        String r = execute.body().string();
        System.out.println("result:" + r);


    }

    /**
     * 文件下载
     */
    public void downLodeFile( ) {
        final String url="http://192.168.3.143:8080/file/Fade.mp3";
        Log.d(TAG, "d: 开始下载"+url);
        Request build = new Request.Builder().url(url).build();
        okHttpClient.newCall(build).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                InputStream fis = body.byteStream();
                File externalFilesDir = getExternalFilesDir(null);
                Log.d(TAG, "onResponse: "+externalFilesDir);
                File file = new File(externalFilesDir, "Fade.mp3");
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int line;
                while ((line = fis.read(bytes)) != -1) {
                    fos.write(bytes,0,line);
                    Log.d(TAG, "onResponse: "+line);
                }
                fis.close();
                fos.flush();
                fos.close();
                Log.d(TAG, "onResponse: 下载成功"+url);
            }
        });
    }
}
